package com.hardware.cipherdriver;

import android.util.Log;

import com.lc.command.CommandActuator;
import com.lc.command.ICommandDriver;
import com.lc.protocol.DeviceError;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;

/**
 * Created by zhyioo on 2018/1/3.
 */

public class CipherDriver implements ICommandDriver {

    public static String TAG = "Cipher";

    protected int _fd = 0;

    protected native int nativeInit(String sArg);

    public CipherDriver() {
        _fd = nativeInit("");
    }

    public native String TransmitCommand(String sModule, String sCmd, String sArg);

    public JSONObject OnCommand(String cmd, JSONObject arg) {
        Log.i(TAG, "Command:" + cmd);

        // SubModule '::'
        int index = cmd.indexOf("::");

        String sModule = "";
        String sCmd = cmd;

        if (index > 0) {
            sModule = cmd.substring(0, index);
            sCmd = cmd.substring(index + 2);
        }
        String sArg = "";
        if (arg != null) {
            sArg = arg.toString();
            Log.i(TAG, "Arguments:" + sArg);
        }
        String sRlt = TransmitCommand(sModule, sCmd, sArg);
        Log.i(TAG, "Result:" + sRlt);

        JSONObject rlt = new JSONObject();
        try {
            rlt = new JSONObject(sRlt);
        } catch (JSONException e) {
            CommandActuator.LogErr(rlt, DeviceError.ArgFormatErr, "JSONException Parse:[" + sRlt + "]");
        }
        return rlt;
    }

    @Override
    public boolean OnCommand(String cmd, JSONObject arg, JSONObject rlt) {
        JSONObject jsonRlt = OnCommand(cmd, arg);
        if(rlt != null) {
            for(Iterator<String> itr = jsonRlt.keys(); itr.hasNext(); ) {
                String key = itr.next();
                try {
                    rlt.put(key, jsonRlt.get(key));
                } catch (JSONException e) {

                }
            }
        }

        int errCode = jsonRlt.optInt("CODE", DeviceError.OperatorErr.ordinal());
        return errCode == DeviceError.Success.ordinal();
    }

    static {
        try {
            System.loadLibrary("CipherDriver");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
